<?php
/**
 * redis操作类
 * User: zyw
 * Date: 16/5/12
 * Time: 下午3:22
 */
class SyncRedis{

    public static $connect = null;

    public function __construct(){

    }
    /**
     * 数据库链接
     * @return PDO
     */
    private static function conn(){
        $redis = new Redis();
        $r= $redis->connect('39.104.100.139',6379);
        $redis->auth('Ots_123');
        if(!$r){
            throw new Exception("redis connect fail!");
        }
        return $redis;
    }

    /**
     * 获取数据链接
     * @return PDO
     */
    public static function getdb(){
        if(self::$connect == null){
            self::$connect = self::conn();
        }
        return self::$connect;
    }

    /**
     * @param $key
     * @param $value
     * @param $timeout
     * @return mixed
     */
    public static  function setData($key,$value, $timeout = 0){
        $r = self::getdb();
        $flag = $r->set($key,$value, $timeout);
        return $flag;
    }

    /**
     * @param $key
     * @return string
     */
    public static  function getData($key){
        $r = self::getdb();
        $str = $r->get($key);
        return $str;
    }

    /**
     * @param $key
     * @return mixed
     */
    public static function delData($key){
        $r = self::getdb();
        $str = $r->delete($key);
        return $str;
    }

    /**
     * 设置hash值
     * @param $key
     * @param $field
     * @param $value
     * @return bool
     */
    public static function setHashData($key, $field, $value){
        $r = self::getdb();
        $r->hset($key, $field, $value);
        return true;
    }

    /**
     * 获取hash
     * @param $key
     * @param $field
     * @return string
     */
    public static function getHashData($key, $field){
        $r = self::getdb();
        return $r->hget($key, $field);
    }

    /**
     * 获取所有的hash值
     * @param $key
     * @return array
     */
    public static function getHashAllData($key){
        $r = self::getdb();
        return $r->hgetall($key);
    }
}